<template>
  <div class="profile-edit-form">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="edit-form"
    >
      <!-- 头像上传区域 -->
      <el-form-item label="头像" prop="avatar">
        <div class="avatar-upload-section">
          <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :headers="uploadHeaders"
              accept="image/jpeg,image/png,image/gif"
          >
            <el-avatar v-if="formData.avatar" :size="100" :src="formData.avatar" class="avatar" />
            <div v-else class="avatar-uploader-trigger">
              <el-icon><Plus /></el-icon>
              <span>上传头像</span>
            </div>
          </el-upload>
          <div class="avatar-tips">
            <p>建议尺寸：100×100像素</p>
            <p>支持 JPG、PNG 格式，大小不超过 2MB</p>
          </div>
        </div>
      </el-form-item>

      <!-- 基本信息字段 -->
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            maxlength="20"
            show-word-limit
            :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item label="个性签名" prop="description">
        <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入个性签名"
            maxlength="100"
            show-word-limit
            :prefix-icon="EditPen"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="formData.email"
            placeholder="请输入邮箱地址"
            :prefix-icon="Message"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            maxlength="11"
            :prefix-icon="Phone"
        />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
          <el-radio label="secret">保密</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="生日" prop="birthday">
        <el-date-picker
            v-model="formData.birthday"
            type="date"
            placeholder="选择生日"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
        />
      </el-form-item>

      <el-form-item label="所在地" prop="location">
        <el-cascader
            v-model="formData.location"
            :options="locationOptions"
            placeholder="请选择所在地"
            :props="cascaderProps"
        />
      </el-form-item>

      <!-- 社交信息 -->
      <el-divider>社交信息</el-divider>

      <el-form-item label="微信" prop="wechat">
        <el-input
            v-model="formData.wechat"
            placeholder="请输入微信号"
            :prefix-icon="ChatDotRound"
        />
      </el-form-item>

      <el-form-item label="QQ" prop="qq">
        <el-input
            v-model="formData.qq"
            placeholder="请输入QQ号"
            :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item label="个人网站" prop="website">
        <el-input
            v-model="formData.website"
            placeholder="请输入个人网站地址"
            :prefix-icon="Link"
        />
      </el-form-item>

      <!-- 表单操作按钮 -->
      <el-form-item class="form-actions">
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
            class="submit-btn"
        >
          <el-icon><Check /></el-icon>
          保存修改
        </el-button>
        <el-button
            @click="handleCancel"
            :disabled="submitting"
            class="cancel-btn"
        >
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button
            type="info"
            @click="handleReset"
            :disabled="submitting"
            class="reset-btn"
        >
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  User,
  EditPen,
  Message,
  Phone,
  Calendar,
  ChatDotRound,
  Link,
  Check,
  Close,
  Refresh,
  Plus
} from '@element-plus/icons-vue'

// 定义Props
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({
      username: '',
      avatar: '',
      description: '',
      email: '',
      phone: '',
      gender: 'secret',
      birthday: '',
      location: [],
      wechat: '',
      qq: '',
      website: ''
    })
  },
  submitting: {
    type: Boolean,
    default: false
  }
})

// 定义Emits
const emit = defineEmits(['update:submitting', 'save', 'cancel'])

// 表单引用
const formRef = ref(null)

// 上传配置
const uploadAction = ref('http://localhost:80/user/avator') // 修改为新的头像上传接口
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token') || localStorage.getItem('satoken')
  return {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'multipart/form-data'
  }
})

// 表单数据
const formData = reactive({ ...props.userInfo })

// 上传状态
const avatarUploading = ref(false)

// 地区选择选项
const locationOptions = ref([
  {
    value: 'beijing',
    label: '北京市',
    children: [
      { value: 'dongcheng', label: '东城区' },
      { value: 'xicheng', label: '西城区' },
      { value: 'chaoyang', label: '朝阳区' },
      { value: 'haidian', label: '海淀区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      { value: 'huangpu', label: '黄浦区' },
      { value: 'xuhui', label: '徐汇区' },
      { value: 'changning', label: '长宁区' },
      { value: 'jingan', label: '静安区' }
    ]
  },
  {
    value: 'guangdong',
    label: '广东省',
    children: [
      { value: 'guangzhou', label: '广州市' },
      { value: 'shenzhen', label: '深圳市' },
      { value: 'zhuhai', label: '珠海市' },
      { value: 'dongguan', label: '东莞市' }
    ]
  }
])

// 级联选择器配置
const cascaderProps = {
  expandTrigger: 'hover',
  value: 'value',
  label: 'label',
  children: 'children'
}

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '个性签名不能超过100个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  wechat: [
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/,
      message: '请输入正确的微信号格式',
      trigger: 'blur'
    }
  ],
  qq: [
    {
      pattern: /^[1-9][0-9]{4,10}$/,
      message: '请输入正确的QQ号格式',
      trigger: 'blur'
    }
  ],
  website: [
    {
      pattern: /^https?:\/\/.+\..+$/,
      message: '请输入正确的网址格式',
      trigger: 'blur'
    }
  ]
})

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG、PNG 或 GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  avatarUploading.value = true
  return true
}

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  avatarUploading.value = false

  // 根据后端响应结构获取头像URL
  if (response && response.code === 0) {
    const avatarUrl = response.data?.url || response.data?.avatarUrl || response.url
    if (avatarUrl) {
      formData.avatar = avatarUrl
      ElMessage.success('头像上传成功')

      // 自动保存头像更改到用户信息
      saveUserInfo()
    } else {
      ElMessage.error('头像上传成功，但未获取到有效URL')
    }
  } else {
    ElMessage.error(response?.message || '头像上传失败')
  }
}

// 头像上传错误处理
const handleAvatarError = (error) => {
  avatarUploading.value = false
  console.error('头像上传错误:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 保存用户信息
const saveUserInfo = async () => {
  emit('update:submitting', true)

  try {
    const token = localStorage.getItem('token') || localStorage.getItem('satoken')
    if (!token) {
      ElMessage.error('未检测到登录信息，请重新登录')
      return
    }

    const response = await axios.post('http://localhost:80/user/update', formData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.status === 200 && response.data.code === 0) {
      ElMessage.success('用户信息更新成功')
      emit('save', { ...formData })

      // 更新本地存储的用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      const updatedUserInfo = { ...userInfo, ...formData }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))

      // 触发全局用户信息更新事件
      window.dispatchEvent(new CustomEvent('userInfoUpdated', {
        detail: updatedUserInfo
      }))
    } else {
      ElMessage.error(response.data.message || '用户信息更新失败')
    }
  } catch (error) {
    console.error('用户信息更新失败:', error)
    ElMessage.error(error.response?.data?.message || '网络错误，请重试')
  } finally {
    emit('update:submitting', false)
  }
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (valid) {
      await ElMessageBox.confirm('确定要保存修改吗？', '确认保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await saveUserInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('表单验证失败，请检查输入内容')
    }
  }
}

// 取消编辑
const handleCancel = () => {
  const hasChanges = JSON.stringify(formData) !== JSON.stringify(props.userInfo)

  if (hasChanges) {
    ElMessageBox.confirm('有未保存的修改，确定要取消吗？', '确认取消', {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }).then(() => {
      emit('cancel')
    }).catch(() => {
      // 用户选择继续编辑
    })
  } else {
    emit('cancel')
  }
}

// 重置表单
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有修改吗？', '确认重置', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    Object.assign(formData, props.userInfo)
    if (formRef.value) {
      formRef.value.clearValidate()
    }
    ElMessage.success('表单已重置')
  }).catch(() => {
    // 用户取消
  })
}

// 监听用户信息变化
onMounted(() => {
  // 初始化表单数据
  Object.assign(formData, props.userInfo)
})
</script>

<style scoped>
.profile-edit-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.edit-form {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-upload-section {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
  font-size: 14px;
}

.avatar-tips {
  flex: 1;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.avatar-tips p {
  margin: 5px 0;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.submit-btn, .cancel-btn, .reset-btn {
  min-width: 100px;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
}

:deep(.el-upload .el-avatar) {
  width: 100%;
  height: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-divider__text) {
  background: white;
  padding: 0 20px;
  color: #409eff;
  font-weight: 500;
}
</style>